﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CP.Entities;
using CP.Win.IViews.GPM;
using CP.Repositories.GPM;
using CP.Utility;

namespace CP.Controllers.GPM
{
    public class WebpartAuthController
    {
        public IWebpartAuthView View { get; private set; }
        public WebpartAuthRepository Repository { get; private set; }

        public WebpartAuthController(IWebpartAuthView view)
        {
            this.View = view;
            Repository = new WebpartAuthRepository();
            this.View.QuerySubmit += OnQuerySubmit;
            this.View.PositionChanged += OnPositionChanged;
            this.View.MenuAuth += new MenuAuthHandler(View_MenuAuth);
            this.View.MenuUnAuth += new MenuUnAuthHandler(View_MenuUnAuth);
            this.View.MenuAuthQuery += new MenuAuthQueryHandler(View_MenuAuthQuery);
            this.View.MenuUnAuthQuery += new MenuUnAuthQueryHandler(View_MenuUnAuthQuery);
        }

        int View_MenuUnAuthQuery(int groupid)
        {
            IList<Menu> unauthmenus = this.Repository.GetUnAuthMenus(groupid);
            this.View.BindUnAuthMenu(unauthmenus);
            return 1;
        }

        int View_MenuAuthQuery(int groupid)
        {
            IList<Menu> authmenus = this.Repository.GetAuthMenus(groupid);
            this.View.BindAuthMenu(authmenus);
            return 1;
        }

        int View_MenuUnAuth(int groupid, IList<string> menus)
        {
            return this.Repository.MenuUnAuth(groupid, menus);
        }

        int View_MenuAuth(int groupid, IList<string> menus)
        {
            return this.Repository.MenuAuth(groupid, menus);
        }

        void OnPositionChanged(object sender, PositionEventArgs e)
        {
            IList<Menu> authmenus = this.Repository.GetAuthMenus(e.GroupID);
            this.View.BindAuthMenu(authmenus);
            IList<Menu> unauthmenus = this.Repository.GetUnAuthMenus(e.GroupID);
            this.View.BindUnAuthMenu(unauthmenus);
        }

        public void Initialize()
        {
            IList<User_Group> groups = this.Repository.GetUser_Groups("");
            this.View.BindUser_Groups(groups);
        }

        void OnQuerySubmit(object sender, QueryEventArgs e)
        {
            QueryUser_Groups(e.QueryConditions);
        }

        private void QueryUser_Groups(QueryCondition condition)
        {
            string sql = "";
            if (null != condition)
                sql = condition.BuildConditionString();
            IList<User_Group> User_Groups = this.Repository.GetUser_Groups(sql);
            this.View.BindUser_Groups(User_Groups);
        }
    }
}
